<template>
	<div v-if="goodInfo" class="home-good-wrap">
		<img @click="onClickLeft" class="left-arrow" :src="goodLeftArrow" alt="">
		<div class="right-arrow">
			<!-- <img  src="../../images/shoucang.png" alt="" v-if="goodInfo.favorite_status!=1" @click="handleFavorite">
			<img v-else src="../../images/shoucang_wc.png" alt=""  @click="handleFavorite"> -->
			<img src="../../images/fenxiang.png" @click="onClickshare" alt="">
		</div>
		<!-- 轮播区 -->
		<van-swipe @change="onChange" class="my-swipe" :autoplay="5000" indicator-color="white">
			<van-swipe-item v-for="(item, index) in goodInfo.banner_list" :key="index">
				<img class="banner-li" :src="item.content" alt="">
			</van-swipe-item>
			<template #indicator>
				<div class="custom-indicator">{{ current + 1 }}/{{ goodInfo.banner_list.length }}</div>
			</template>
		</van-swipe>

		<div class="good-cash" v-if="goodInfo.xjq_deduction > 0">
			<img class="cash-bg" src="../../images/mine/cash-bg.png" alt="">
			<div class="cash-content">
				<div>现金券最多可抵扣</div>
				<div class="cash-price">¥{{ goodInfo.xjq_deduction }}</div>
			</div>
		</div>
		<!-- 商品信息 -->
		<div class="good-data" :class="{'cashClass': goodInfo.xjq_deduction > 0}">
			<div class="good-name">
				{{ goodInfo.name }}
			</div>
			<div class="good-price">
				<div class="good-left">
					<!--  -->
					<div class="good-price-sys">
						<div v-if="goodInfo.price > 0"><span style="font-size: .28rem;">¥</span>{{ goodInfo.price }}
						</div>
						<div class="hd_box" v-if="goodInfo.price_integral > 0">
							<span v-if="goodInfo.price > 0">+</span>
							<div class="hd_text"><img src="../../images/huaduo_icon.png" alt="">{{
								goodInfo.price_integral }}</div>
						</div>
					</div>
					<div class="good-price-sale">销量:<span>{{ goodInfo.sales_count }}</span></div>
					<div class="good-info-num" v-if="goodInfo.labels && goodInfo.labels.length">
						{{ goodInfo.labels[0].name }}
					</div>
				</div>
				<!-- <div v-if="goodInfo.labels.length" class="good-subsidy-btn">{{ goodInfo.labels[0].name }}</div> -->
			</div>
			<!-- <div class="good-info-subsidy" v-if="goodInfo.labels.length">
				<div class="good-info-subsidy-btn" :style="{background:item.bg_color,color:item.color}" v-for="item,index in goodInfo.labels" :key="index">
					<img v-if="item.icon_type!=0" :src="item.icon_type==1?require('../../images/xiaofei.png'):require('../../images/huaduo.png')" alt="">{{ item.name }}</div>
			</div> -->
		</div>

		<!-- 发货规格 -->
		<div class="good-cl">

			<div v-if="goodInfo.not_shipped_region" @click="handleToNoRegion" class="good-ceil">
				<img class="good-ceil-icon" :src="goodAdressIcon" alt="">
				<div class="good-ceil-label">不发货地区：</div>
				<div class="good-ceil-val">{{ goodInfo.not_shipped_region }}</div>
				<img class="good-ceil-arrow" :src="goodCeilArrow" alt="">
			</div>
			<div @click="handleToSku" class="good-ceil">
				<img class="good-ceil-icon" :src="goodSkuIcon" alt="">
				<div class="good-ceil-label">规格数量选择</div>
				<div class="good-ceil-val"></div>
				<img class="good-ceil-arrow" :src="goodCeilArrow" alt="">
			</div>
			<!-- <div class="good-ceil">
				<img class="good-ceil-icon" :src="goodShopIcon" alt="">
				<div class="good-ceil-label">{{ goodInfo.shop_name }}</div>

				<div @click="handleToShop" class="arrow-right-box">
					<div class="arrow-right-text">进店查看</div>
					<img class="good-ceil-arrow" :src="goodCeilArrow" alt="">
				</div>
			</div> -->
		</div>

		<div class="good-detail">
			<img class="good-detail-icon" :src="goodDetailIcon" alt="">

			<img v-for="(item, index) in goodInfo.content_list" :key="index" :src="item.content" alt=""
				class="good-detail-img">
		</div>


		<!-- 底部 -->
		<div class="good-action">
			<div @click="handleToAdd" class="good-action-cart active-btn">加入购物车</div>
			<div @click="handleToBuy" class="good-action-buy active-btn">
				<div>立即购买</div>
				<div v-if="goodInfo.commission_share > 0" style="font-size: .24rem; line-height: .34rem;">分享赚￥{{
					goodInfo.commission_share }}</div>
			</div>
		</div>


		<!-- sku -->
		<sku-box v-if="goodInfo && goodSpec" ref="sku" :mode="mode" :mainPrice="goodInfo.price"
			:mainIntegral="goodInfo.price_integral" :stock="goodInfo.store_count" :goodSpec="goodSpec"
			:contribution="goodInfo.labels && goodInfo.labels.length ? goodInfo.labels[0].name : ''" @addCart="addCart"
			@toBuy="toBuy"></sku-box>


	</div>
</template>

<script>
import { GOOD, GOOD_SPEC, GOOD_CART_ADD, GOODS_FAVORITE_OPERATE } from '@/api/home';
import {
	goodLeftArrow, goodAdressIcon, goodSkuIcon,
	goodShopIcon, goodCeilArrow, goodDetailIcon
} from '@/tool/static-img';
import skuBox from './components/sku-box';

import wx from 'weixin-js-sdk';
import { SHARE_JSAPI } from '@/api/cms';
export default {
	components: {
		skuBox
	},
	data() {
		return {
			goodLeftArrow, goodAdressIcon, goodSkuIcon, goodShopIcon,
			goodCeilArrow, goodDetailIcon,
			id: '',
			current: 0,
			goodInfo: null,
			goodSpec: null,
			// sku 模式
			mode: '',
			loadBtn: false
		}
	},
	async created() {

		this.id = this.$route.query.id;

		if (this.$route.query.invite_code) {
			localStorage.setItem('invite_code', this.$route.query.invite_code);
		}
		// 商品详情
		await this.getGoodDetail();

		// 商品规格
		this.getGoodSpec();

		// 数据记录删除
		localStorage.removeItem('hasSelectAddress');

		// 分享配置
		// this.shareAjax();
	},
	methods: {

		// 分享
		onClickshare() {
			// this.shareAjax();
			// 调用buildShareLink获取分享链接
			// const shareLink = this.buildShareLink();
			const shareLink = this.goodInfo.share_config.share_url;
			
			// 复制链接到剪贴板
			const textArea = document.createElement('textarea');
			textArea.value = shareLink;
			document.body.appendChild(textArea);
			textArea.select();
			document.execCommand('copy');
			document.body.removeChild(textArea);
			
			// 显示toast提示
			this.$toast('链接已复制，可直接分享');
		},

		// 构建分享链接
		buildShareLink() {
			// const shareLink = this.goodInfo.share_config.share_url;
			// 从路由参数获取商品ID
			// const goodsId = this.id;
			// // 从localStorage获取邀请码
			// const inviteCode = localStorage.getItem('invite_code') || '';
			// // 获取当前页面完整URL，并保留hash部分(#后的路由)
			// const currentUrl = location.href;

			// // 确保保留hash部分，正确构建基础URL
			// let baseUrl;
			// if (currentUrl.includes('#')) {
			// 	// 对于Vue单页应用，我们需要保留hash部分
			// 	baseUrl = currentUrl.split('?')[0];
			// } else {
			// 	baseUrl = currentUrl.split('?')[0];
			// }

			// // 构建带商品ID和邀请码的完整链接
			// let shareLink = `${baseUrl}?id=${goodsId}&invite_code=${inviteCode}`;
			// console.log('构建的分享链接:', shareLink);

			// return shareLink;
		},

		// 获取分享签名
		shareAjax() {
			let params = {};
			// const shareLink = this.goodInfo.share_config.share_url;
			// // 关键修改：使用当前页面URL（去掉hash部分）进行签名
			// params['url'] = shareLink
			// params['url'] = encodeURI(shareLink.split('#')[0]);
			// params['url'] = encodeURI(location.href.split('#')[0]);
			params['url'] = encodeURI(location.href.split('#')[0]);

			console.log('签名URL:', params['url']);

			this.$http.post(SHARE_JSAPI, params)
				.then(res => {
					console.log('分享配置返回:', res.data);
					this.shareWx(res.data);
				})
				.catch((error) => {
					console.log('分享接口调用失败:', error);
					this.$toast.fail('分享配置失败');
				})
		},
		shareWx(wxInfo) { // 分享配置
			// 构建分享链接
			// const shareLink = this.buildShareLink();
			var obj = {
				title: this.goodInfo.name, //标题
				desc: this.goodInfo.shop_name, //描述
				link: location.href + "&share=1" + (wxInfo.invite_code == '' ? '' : "&invite_code=" + wxInfo.invite_code),
				imgUrl: this.goodInfo.cover_url
			};
			console.log('分享参数:', obj);
			this.wxshareConfig(wxInfo, obj);

			//   console.log(obj, 'jj')
		},
		wxshareConfig(wxInfo, obj) {
			console.log('微信配置参数:', wxInfo);
			wx.config({
				debug: true, // 启用调试模式，方便排查问题
				appId: wxInfo.app_id, //appId
				timestamp: wxInfo.timestamp, //时间戳
				nonceStr: wxInfo.noncestr, //加密需要字符串(自己定义的)
				signature: wxInfo.signature, //sha1加密后字符串
				jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData','onMenuShareTimeline', 'onMenuShareAppMessage',]
			});

			console.log(obj, '配置信息')

			wx.error(function (res) {
				console.log('link是: ' + obj.link)
				console.log(res, '分享配置报错')
				this.$toast.fail('微信分享配置失败');
			})

			wx.ready(function () {
				console.log('微信配置成功，开始设置分享');

				// 新版本API - 分享给朋友
				wx.updateAppMessageShareData({
					title: obj.title, // 分享标题
					desc: obj.desc, // 分享描述
					link: obj.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl: obj.imgUrl, // 分享图标
					success: function () {
						console.log('设置朋友分享成功')
					},
					fail: function (res) {
						console.error('设置朋友分享失败:', res);
					}
				})

				// 新版本API - 分享到朋友圈
				wx.updateTimelineShareData({
					title: obj.title, // 分享标题
					link: obj.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl: obj.imgUrl, // 分享图标
					success: function () {
						console.log('设置朋友圈分享成功')
					},
					fail: function (res) {
						console.error('设置朋友圈分享失败:', res);
					}
				})

				// 兼容旧版本API - 分享给朋友
				if (wx.onMenuShareAppMessage) {
					wx.onMenuShareAppMessage({
						title: obj.title,
						desc: obj.desc,
						link: obj.link,
						imgUrl: obj.imgUrl,
						success: function () {
							console.log('旧版朋友分享成功');
						},
						cancel: function () {
							console.log('用户取消分享');
						}
					});
				}

				// 兼容旧版本API - 分享到朋友圈
				if (wx.onMenuShareTimeline) {
					wx.onMenuShareTimeline({
						title: obj.title,
						link: obj.link,
						imgUrl: obj.imgUrl,
						success: function () {
							console.log('旧版朋友圈分享成功');
						},
						cancel: function () {
							console.log('用户取消分享');
						}
					});
				}

			})
		},

		onClickLeft() {
			if (localStorage.getItem('goodmsg') == 1) {
				this.$router.go(-1)
				localStorage.removeItem('goodmsg')
			} else {
				if (this.$route.query.share) {
					this.$router.replace({
						name: 'home'
					})
				} else {
					this.$router.replace({
						name: 'home'
					})
				}
			}
		},
		//收藏
		handleFavorite() {
			this.$http.post(GOODS_FAVORITE_OPERATE, { goods_id: this.id })
				.then(res => {
					this.$toast.success(res.message)
					// 商品详情
					this.getGoodDetail();

					// 商品规格
					this.getGoodSpec();
				})
		},
		onChange(index) {
			this.current = index;
		},
		// 商品详情
		async getGoodDetail() {
			const {
				data
			} = await this.$http.get(GOOD + this.id)


			this.goodInfo = data;

		},
		// 不发货地区
		handleToNoRegion() {
			localStorage.setItem('noRegion', this.goodInfo.not_shipped_region)
			this.$router.push({
				name: 'noRegion'
			})
		},
		// 进店查看
		handleToShop() {
			localStorage.setItem('shopInfoName', this.goodInfo.shop_name)
			this.$router.push({
				name: 'shopInfoTwo',
				query: {
					id: this.goodInfo.shop_id
				}
			})
		},
		// 商品规格
		getGoodSpec() {
			this.$http.get(GOOD_SPEC + this.id)
				.then(res => {
					const {
						data
					} = res;

					this.goodSpec = data;

					this.getSkuData();
				})
		},
		// sku 数据处理
		getSkuData() {
			// sku数据
			if (!this.goodSpec) {
				return;
			}

			// 初始化sku数据
			setTimeout(() => {
				this.$refs['sku'].init();
			}, 100)

		},
		// 是否登录
		isLogin() {
			const token = localStorage.getItem('token');
			if (!token) {
				console.log(this.$route);
				localStorage.setItem('redirect', this.$route.fullPath)
				// 对于未登录用户，直接跳转到注册页面，并传递邀请码
				const inviteCode = this.$route.query.inviteCode || '';

				this.$router.push({
					// name: 'login'
					name: 'register',
					query: {
						inviteCode: inviteCode
					}
				})
				return false;
			}

			return true;
		},
		// 加入购物车
		handleToAdd() {
			if (!this.isLogin()) {
				return
			}

			this.mode = 'cart';

			this.$refs['sku'].show = true;
		},
		// 立即购买
		handleToBuy() {
			if (!this.isLogin()) {
				return
			}

			this.mode = 'buy';
			this.$refs['sku'].show = true;
		},
		// 打开规格
		handleToSku() {
			if (!this.isLogin()) {
				return
			}

			this.mode = '';
			this.$refs['sku'].show = true;
		},
		// 加入购物车
		addCart(data) {
			if (this.loadBtn) {
				return
			}
			this.loadBtn = true;
			this.$http.post(GOOD_CART_ADD, data)
				.then(() => {
					this.$refs['sku'].show = false;

					this.$toast.success('加入购物车成功');
				})
				.finally(() => {
					this.loadBtn = false;
				})
		},
		// 去下单
		toBuy(data) {
			this.$refs['sku'].show = false;

			localStorage.setItem('orderItem', JSON.stringify({
				...data,
				from_cart: 0,
				goods_id: this.id,
			}))

			this.$router.push({
				name: 'order'
			})
		},
	}

}
</script>

<style lang="scss">
.home-good-wrap {
	position: relative;
	min-height: 100vh;
	background-color: #ffffff;
	padding-bottom: calc(1.2rem + constant(safe-area-inset-bottom));
	padding-bottom: calc(1.2rem + env(safe-area-inset-bottom));
	box-sizing: border-box;

	.left-arrow {
		position: fixed;
		left: 0.32rem;
		top: 0.14rem;
		z-index: 1;
		width: 0.6rem;
		height: 0.6rem;
	}

	.right-arrow {
		position: fixed;
		right: 0.32rem;
		top: 0.14rem;
		z-index: 1;
		width: 0.6rem;
		height: 0.6rem;
		display: flex;

		img {
			width: 100%;
			height: 100%;
			margin-right: .32rem;
		}
	}

	.my-swipe {
		position: relative;
		width: 7.5rem;
		height: 7.5rem;

		.banner-li {
			display: block;
			width: 7.5rem;
			height: 7.5rem;
		}

		.custom-indicator {
			display: flex;
			align-items: center;
			justify-content: center;
			position: absolute;
			bottom: 0.32rem;
			right: 0.32rem;
			width: 0.7rem;
			height: 0.36rem;
			font-weight: 400;
			font-size: 0.24rem;
			color: #ffffff;
			background-color: rgba(51, 51, 51, 0.7);
			border-radius: 0.18rem;
		}
	}

	.good-cash {
		position: relative;
		width: 100%;
		height: 1.96rem;
		img {
			width: 100%;
			height: 100%;
		}

		.cash-content {
			position: absolute;
			left: 0.5rem;
			top: 0.2rem;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 0.28rem;
			color: #ffffff;
			line-height: 0.32rem;
			.cash-price {
				margin-top: 0.06rem;
				font-size: 0.48rem;
				font-weight: 600;
				line-height: 0.66rem;
			}
		}
	}
	.cashClass{
		position: relative;
		z-index: 10;
		margin-top: -0.6rem;
	}

	.good-data {
		
		background-color: #ffffff;
		border-radius: 0.24rem 0.24rem 0 0;
		padding: 0.32rem;

		.good-name {
			margin-bottom: 0.16rem;
			font-family: PingFangSC, PingFang SC;
			line-height: 0.44rem;
			font-size: 0.32rem;
			font-weight: 500;
			color: #333333;
		}

		.good-price {
			display: flex;
			align-items: center;
			justify-content: space-between;
			position: relative;

			.good-left {
				display: flex;
				align-items: center;

				.good-info-num {
					position: absolute;
					right: 0;
					border-radius: .06rem;
					border: 1px solid #31A653;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: .22rem;
					padding: 0 .12rem;
					color: #31A653;
				}

				.good-price-sys {
					height: 0.52rem;
					line-height: 0.52rem;
					margin-right: 0.2rem;
					font-weight: 500;
					font-size: 0.48rem;
					color: #31A653;
					display: flex;
					align-items: center;
					justify-content: center;

					.hd_box {
						display: flex;

						span {
							font-size: .28rem;
							height: .32rem;
							line-height: .3rem;
							color: #FF6200;
							margin-left: .04rem;
							margin-right: .04rem;
						}

						img {
							width: .32rem;
							height: .32rem;
							vertical-align: middle;
							margin-right: .03rem;
						}

						.hd_text {
							font-size: .32rem;
							height: .32rem;
							color: #FF6200;
							display: flex;
							align-items: center;
							justify-content: center;

						}
					}

					// &::before {
					// 	content: '¥';
					// 	font-size: 0.28rem;
					// }
				}

				.good-price-sale {
					height: 0.34rem;
					padding-top: 0.02rem;
					line-height: 0.34rem;
					font-weight: 400;
					font-size: 0.24rem;
					color: #999999;
				}
			}
		}

		.good-info-subsidy {
			display: inline-block;
			// height: 0.36rem;
			margin-top: 0.08rem;

			.good-info-subsidy-btn {
				img {
					width: .32rem;
					height: .32rem;
					// vertical-align: middle;
				}

				display: flex;
				margin-top: .1rem;
				// background: #fcf0ef;
				// color: #F32A23;
				align-items: center;
				height: 0.36rem;
				font-weight: 400;
				font-size: 0.22rem;
				border-radius: 0.06rem;
				text-indent: .1rem;
				box-sizing: border-box;
			}

			.hd_bt {
				background: #fdf4ee;
				color: #FF6200;
			}
		}
	}

	.good-cl {
		width: 7.02rem;
		margin: auto;
		background: #f6f6f6;
		border-radius: 0.16rem;

		.good-ceil {
			position: relative;
			display: flex;
			align-items: center;
			height: 1.02rem;
			border-bottom: 0.01rem solid #e3e3e3;

			&:last-child {
				border: none;
			}

			.arrow-right-box {
				position: absolute;
				right: 0.24rem;
				top: 0;
				bottom: 0;
				margin: auto;
				display: flex;
				align-items: center;
				font-size: 0.28rem;
				color: #666666;

				.arrow-right-text {
					margin-right: 0.08rem;
				}

				.good-ceil-arrow {
					width: 0.32rem;
					height: 0.32rem;
				}
			}


			.good-ceil-icon {
				width: 0.32rem;
				height: 0.32rem;
				margin-right: 0.16rem;
				margin-left: 0.24rem;
			}

			.good-ceil-label {
				max-width: 3.88rem;
				flex-shrink: 0;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 0.28rem;
				color: #333333;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				word-break: break-all;
			}

			.good-ceil-val {
				flex-shrink: 0;
				width: 3.88rem;
				margin-right: 0.18rem;
				font-weight: 400;
				font-size: 0.28rem;
				color: #666666;

				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				word-break: break-all;
			}

			.good-ceil-text {
				text-align: right;
			}

			.good-ceil-arrow {
				width: 0.32rem;
				height: 0.32rem;
			}
		}

	}

	.good-detail {
		.good-detail-icon {
			display: block;
			width: 1.84rem;
			height: 0.44rem;
			margin: auto;
			margin-top: 0.28rem;
			margin-bottom: 0.24rem;
		}

		.good-detail-img {
			display: block;
			width: 7.02rem;
			margin: auto;
		}
	}

	.good-action {
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 7.5rem;
		height: 1.08rem;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		background: #ffffff;

		.good-action-cart {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 3.4rem;
			height: 0.88rem;
			margin-left: 0.24rem;
			font-size: 0.32rem;
			font-weight: 500;
			font-family: PingFangSC, PingFang SC;
			color: #ffffff;
			background: #FFB900;
			border-radius: 0.44rem;
		}

		.good-action-buy {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 3.4rem;
			height: 0.88rem;
			margin-right: 0.24rem;
			font-size: 0.32rem;
			font-weight: 500;
			font-family: PingFangSC, PingFang SC;
			color: #ffffff;
			background: linear-gradient(90deg, #75BE70 0%, #56AE48 100%);
			border-radius: 0.44rem;
		}
	}
}
</style>